<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>股票分析系统 - 展示页</title>
  <!-- 引入 Bootstrap CSS -->
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
  <script src="./js/axios.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="./js/vue.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  <title>设置淡色背景</title>
  <style>
      body {
          background-color: #fffae8; 
      }
      .container {
          min-height: 100vh;
          padding-bottom: 100px; /* 确保底部有足够的空间 */
      }
      .chart-container {
          height: 800px; /* 调整高度以确保图表能完整显示 */
          width: 100%;
      }
  </style>
</head>
<body>
  <div id="app">
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="#">股票分析系统</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link" href="index.html">首页</a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="kline1.html">展示页<span class="sr-only">(当前)</span></a>
        </li>
  	  <li class="nav-item">
  	    <a class="nav-link" href="data.html">数据获取</a>
  	  </li>
        <li class="nav-item">
          <a class="nav-link" href="register.html">注册</a>
        </li>
        <li class="nav-item ">
          <a class="nav-link" href="login.html">登录</a>
        </li>
  	  
      </ul>
    </div>
  </nav>

    <div class="container mt-5">
      <div class="row justify-content-center">
        <div class="col-md-8">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title text-center">股票数据查询</h5>
              <form @submit.prevent="loadechars">
                <div class="form-group">
                  <label for="startDate">开始时间</label>
                  <input type="date" v-model="startDate" class="form-control" id="startDate" required>
                </div>
                <div class="form-group">
                  <label for="endDate">结束时间</label>
                  <input type="date" v-model="endDate" class="form-control" id="endDate" required>
                </div>
                <div class="form-group">
                  <label for="gpName">股票名称</label>
                  <input type="text" v-model="gpName" class="form-control" id="gpName" placeholder="请输入股票名称" required>
                </div>
                <button type="submit" class="btn btn-primary btn-block">查询</button>
              </form>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-5">
        <div id="main" class="chart-container"></div>
      </div>
    </div>
  </div>

  <!-- 引入 jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <!-- 引入 Popper.js -->
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
  <!-- 引入 Bootstrap JS -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <script type="text/javascript">
    new Vue({
      el: "#app",
      data: {
        option: {
          xAxis: [
            {
              gridIndex: 0,
              data: []
            },
            {
              gridIndex: 1,
              data: []
            },
            {
              gridIndex: 2,
              data: []
            },
            {
              gridIndex: 3,
              data: []
            },
            {
              gridIndex: 4,
              data: []
            }
          ],
          yAxis: [
            {
              scale: true,
              gridIndex: 0
            },
            {
              scale: true,
              gridIndex: 1
            },
            {
              scale: true,
              gridIndex: 2
            },
            {
              scale: true,
              gridIndex: 3
            },
            {
              scale: true,
              gridIndex: 4
            }
          ],
          grid: [
            {
              left: 20,
              right: 20,
              top: 110,
              height: 120
            },
            {
              left: 20,
              right: 20,
              top: 260,
              height: 40
            },
            {
              left: 20,
              right: 20,
              top: 320,
              height: 120
            },
            {
              left: 20,
              right: 20,
              top: 480,
              height: 80
            },
            {
              left: 20,
              right: 20,
              top: 580,
              height: 120
            }
          ],
          legend: {
            data: ['成交量', 'K线', '5日均线', 'RSI', 'MACD', 'Bollinger Bands']
          },
          tooltip: {
            trigger: 'axis'
          },
          series: [
            {
              name: "K线",
              type: 'candlestick',
              xAxisIndex: 0,
              yAxisIndex: 0,
              data: []
            },
            {
              name: "成交量",
              type: 'bar',
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: []
            },
            {
              name: "5日均线",
              type: 'line',
              xAxisIndex: 0,
              yAxisIndex: 0,
              data: []
            },
            {
              name: "RSI",
              type: 'line',
              xAxisIndex: 2,
              yAxisIndex: 2,
              data: []
            },
            {
              name: "MACD",
              type: 'bar',
              xAxisIndex: 3,
              yAxisIndex: 3,
              data: []
            },
            {
              name: "MACD Signal",
              type: 'line',
              xAxisIndex: 3,
              yAxisIndex: 3,
              data: []
            },
            {
              name: "MACD Histogram",
              type: 'bar',
              xAxisIndex: 3,
              yAxisIndex: 3,
              data: []
            },
            {
              name: "Bollinger Upper",
              type: 'line',
              xAxisIndex: 4,
              yAxisIndex: 4,
              data: []
            },
            {
              name: "Bollinger Middle",
              type: 'line',
              xAxisIndex: 4,
              yAxisIndex: 4,
              data: []
            },
            {
              name: "Bollinger Lower",
              type: 'line',
              xAxisIndex: 4,
              yAxisIndex: 4,
              data: []
            }
          ]
        },
        startDate: '',
        endDate: '',
        gpName: ''
      },
      methods: {
        formatDate(date) {
          const d = new Date(date);
          const year = d.getFullYear();
          const month = (d.getMonth() + 1).toString().padStart(2, '0');
          const day = d.getDate().toString().padStart(2, '0');
          return `${year}${month}${day}`;
        },
        loadechars() {
          var chartDom = document.getElementById('main');
          var myChart = echarts.init(chartDom);
          let startDate = this.formatDate(this.startDate);
          let endDate = this.formatDate(this.endDate);
          let gpName = this.gpName;
  
          axios.get(`http://127.0.0.1/getStocks?startDate=${startDate}&endDate=${endDate}&pageNow=1&gpName=${gpName}`)
            .then(response => {
              let xdata = [];
              let klinedata = [];
              let chengjiaoliang = [];
              let mv5 = [];
              let rsi = [];
              let macd = [];
              let macdSignal = [];
              let macdHistogram = [];
              let bollingerUpper = [];
              let bollingerMiddle = [];
              let bollingerLower = [];
  
              let closePrices = [];
              let shortEMA = [];
              let longEMA = [];
  
              let jsonarr = response.data;
  
              for (let i = 0; i < jsonarr.length; i++) {
                let json = jsonarr[i];
  
                let closePrice = parseFloat(json.table_stock_closePrice);
                closePrices.push(closePrice);
  
                if (i >= 4) {
                  let start = i - 4;
                  let sum_close_5 = 0;
                  for (let index = start; index <= i; index++) {
                    let jsonObject = jsonarr[index];
                    let closePrice = parseFloat(jsonObject.table_stock_closePrice);
                    sum_close_5 += closePrice;
                  }
                  mv5.push(sum_close_5 / 5);
                } else {
                  mv5.push(null);
                }
  
                // 计算RSI
                if (i >= 13) {
                  let gain = 0;
                  let loss = 0;
                  for (let j = i - 13; j <= i; j++) {
                    let change = closePrices[j] - closePrices[j - 1];
                    if (change > 0) {
                      gain += change;
                    } else {
                      loss -= change;
                    }
                  }
                  let avgGain = gain / 14;
                  let avgLoss = loss / 14;
                  let rs = avgGain / avgLoss;
                  rsi.push(100 - (100 / (1 + rs)));
                } else {
                  rsi.push(null);
                }
  
                // 计算MACD
                let shortPeriod = 12;
                let longPeriod = 26;
                let signalPeriod = 9;
  
                if (i >= shortPeriod - 1) {
                  let sumShort = 0;
                  for (let j = i - (shortPeriod - 1); j <= i; j++) {
                    sumShort += closePrices[j];
                  }
                  shortEMA.push(sumShort / shortPeriod);
                } else {
                  shortEMA.push(null);
                }
  
                if (i >= longPeriod - 1) {
                  let sumLong = 0;
                  for (let j = i - (longPeriod - 1); j <= i; j++) {
                    sumLong += closePrices[j];
                  }
                  longEMA.push(sumLong / longPeriod);
                } else {
                  longEMA.push(null);
                }
  
                if (shortEMA[i] != null && longEMA[i] != null) {
                  let macdValue = shortEMA[i] - longEMA[i];
                  macd.push(macdValue);
  
                  if (i >= longPeriod + signalPeriod - 2) {
                    let sumSignal = 0;
                    for (let j = i - (signalPeriod - 1); j <= i; j++) {
                      sumSignal += macd[j];
                    }
                    macdSignal.push(sumSignal / signalPeriod);
                    macdHistogram.push(macdValue - (sumSignal / signalPeriod));
                  } else {
                    macdSignal.push(null);
                    macdHistogram.push(null);
                  }
                } else {
                  macd.push(null);
                  macdSignal.push(null);
                  macdHistogram.push(null);
                }
  
                // 计算布林带
                if (i >= 19) {
                  let sumMiddle = 0;
                  for (let j = i - 19; j <= i; j++) {
                    sumMiddle += closePrices[j];
                  }
                  let middle = sumMiddle / 20;
                  bollingerMiddle.push(middle);
  
                  let sumUpper = 0;
                  let sumLower = 0;
                  for (let j = i - 19; j <= i; j++) {
                    sumUpper += Math.pow(closePrices[j] - middle, 2);
                    sumLower += Math.pow(closePrices[j] - middle, 2);
                  }
                  let stddev = Math.sqrt(sumUpper / 20);
                  bollingerUpper.push(middle + (2 * stddev));
                  bollingerLower.push(middle - (2 * stddev));
                } else {
                  bollingerMiddle.push(null);
                  bollingerUpper.push(null);
                  bollingerLower.push(null);
                }
  
                xdata.push(json.date);
                klinedata.push([
                  parseFloat(json.table_stock_openPrice),
                  parseFloat(json.table_stock_closePrice),
                  parseFloat(json.table_stock_hiPrice),
                  parseFloat(json.table_stock_lowPrice)
                ]);
                chengjiaoliang.push(parseFloat(json.table_stock_volume));
              }
  
              this.option.xAxis[0].data = xdata;
              this.option.xAxis[1].data = xdata;
              this.option.xAxis[2].data = xdata;
              this.option.xAxis[3].data = xdata;
              this.option.xAxis[4].data = xdata;
              this.option.series[0].data = klinedata;
              this.option.series[1].data = chengjiaoliang;
              this.option.series[2].data = mv5;
              this.option.series[3].data = rsi;
              this.option.series[4].data = macd;
              this.option.series[5].data = macdSignal;
              this.option.series[6].data = macdHistogram;
              this.option.series[7].data = bollingerUpper;
              this.option.series[8].data = bollingerMiddle;
              this.option.series[9].data = bollingerLower;
  
              myChart.setOption(this.option);
            })
            .catch(error => {
              console.error("There was an error loading the chart data!", error);
            });
        }
      }
    })
  </script>
</body>
</html>
